<?php
/**
 * 
 * @author yuxun
 *
 */

class ModInside extends Model {

    protected $table = 'inside';

    // 表名
    public function tableName(){
        return $this->table;
    }

    public static function model($className=__CLASS__){
        return parent::model($className);
    }

    public function getDbConnection(){
        return Yii::app()->dbOss;
    }

    public function addmuch($params){
    	$result = $this->getDbConnection()->multiInsert($params, $this->table, FALSE);
    	return $result;
    }
    
    public function select($params){
    	$table = $this->table;
    	$where  = ' WHERE game=:game ';
    	$args   = array(
    			':game'     => $params['g']
    	);
    
    	if(!empty($params['openid'])){
    		$where .= " AND openid like :openid ";
    		$args['openid'] = '%'.$params['openid'].'%';
    	}    	 

    	$fields = "*";
    	$sql = "SELECT {$fields} FROM {$table} {$where}";
    	$data = $this->getDbConnection()->query($sql, $args);    	
    	return $data;
    }
    
    public function page($params){
    	$table = $this->table;
    	$where  = ' WHERE game=:game ';
    	$args   = array(
    			':game'     => $params['g']
    	);
    	
        if(!empty($params['openid'])){
    		$where .= " AND openid like :openid ";
    		$args['openid'] = '%'.$params['openid'].'%';
    	}  
    	
    	$c_sql = "select count(1) as cnt from {$table} {$where}";
    	$c_result = $this->getDbConnection()->query($c_sql, $args);
    	$count = isset($c_result[0]['cnt']) ? $c_result[0]['cnt'] : 0;

    	$order  = self::getOrder($params['order']);
    	$limit  = PubFunc::getLimit($params['length'], $params['page']);
    	$fields = "*";
    	$sql = "SELECT {$fields} FROM {$table} {$where} {$order} {$limit}";
    	
    	$data = $this->getDbConnection()->query($sql, $args);
    	$result = array('count'=>$count,'data'=>$data);
    	return $result;
    }
    
    public static function getOrder($order){
    	if(PubFunc::checkEmpty($order, array(0, 1))) return '';
    	if(!in_array($order[1], array('asc', 'desc'))){
    		$sort = 'asc';
    	}else{
    		$sort = $order[1];
    	}
    	return " ORDER BY {$order[0]} {$sort} ";
    }
    
    public function repeat($id,$field,$val,$g){
    	$sql = "SELECT count(1) as cnt FROM {$this->table} where id != {$id} and {$field} = '{$val}' and game = '{$g}'";
    	$c_result = $this->getDbConnection()->getAll($sql, $args);
    	$count = isset($c_result[0]['cnt']) ? $c_result[0]['cnt'] : 0;
    	return $count;
    }
    
    
} 